//
//  FocusDoctorController.m
//  QuickCure1
//
//  Created by maoge on 16/10/30.
//  Copyright © 2016年 maoge. All rights reserved.
//

#import "FocusDoctorController.h"

#import "FocusDoctorData.h"
#import "YYModel.h"
#import "NetWorkTool.h"
#import "FocusDoctorCell.h"
#import "FocusDoctorDetailController.h"
#import"DataBaseManager.h"
#import "AppDelegate.h"


//#import "FocusDoctorDetailData.h"



@interface FocusDoctorController ()<UITableViewDelegate,UITableViewDataSource,deleteDatalist>


//@property(nonatomic,strong)NSMutableArray*dataList;
@property(nonatomic,weak)UITableView*tableView;

@property(nonatomic,strong)NSIndexPath*index;

@end
static NSString*cellID=@"DoctorListCellID";

@implementation FocusDoctorController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self loadData];
    
}


#pragma mark - 初始化界面
-(void)setupUI
{
    self.title=@"选择医生";
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    NSDictionary*dict=@{NSFontAttributeName:[UIFont systemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]};
    [self.navigationController.navigationBar setTitleTextAttributes:dict];

    
    UITableView *table = [[UITableView alloc] init];
    self.tableView = table;
    
    [self.view addSubview:table];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //自动行高
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 80;
    
    //注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"FocusDoctorCell" bundle:nil] forCellReuseIdentifier:cellID];
    
    [table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}
//15.获取关注医生列表接口
-(void)test15{
    
    //    请求地址: http://iosapi.itcast.cn/doctorList.json.php
    //    请求参数:{"user_id":1000089,"page_size":15,"page":1}
    
    NSString *urlString = kDoctorListUrl;
    NSDictionary *paramDic = @{
                               @"user_id":@"1000089",
                               @"page_size":@15,
                               @"page":@1
                               };
    
    
    [self loadUrl:urlString params:paramDic];
    
}

#pragma mark - 删除关注医生列表的网络请求

-(void)test14{
    //    请求地址: http://iosapi.itcast.cn/deleteDoctor.json.php
    //    请求参数:{"user_id":1000089,"doctor_id":300000315}
    
    NSString *urlString = kDeleteDoctorUrl;
    NSDictionary *paramDic = @{
                               @"user_id":@"1000089",
                               @"doctor_id":@300000315
                               };
    
//    [self loadUrl:urlString params:paramDic];
    
    [[NetWorkTool shareManager] POST_RequestWithUrlString:urlString parmas:paramDic successBloock:^(id responseObject) {
        
        NSLog(@"responseObject = %@",responseObject);
    } failureBlock:^(NSError *error) {
        
        NSLog(@"error = %@",error);
    }];

}

#pragma mark - 初始化数据模型列表
-(NSMutableArray<FocusDoctorData*>*)dataList
{
    if (!_dataList)
    {
        _dataList=[[NSMutableArray alloc]init];
        
    }
    return _dataList;
}


#pragma mark - 获取关注医生的接口
-(void)loadData{
    
    //    请求地址: http://iosapi.itcast.cn/doctorList.json.php
    //    请求参数:{"user_id":1000089,"page_size":15,"page":1}
    
//    [self loadDataBase];
//    if (self.dataList.count>5) {
//        [self.tableView reloadData];
//        return;
//    }

    
    NSString *urlString = kDoctorListUrl;
    NSDictionary *paramDic = @{
                               @"user_id":@"1000089",
                               @"page_size":@15,
                               @"page":@1
                               };
    
//    NSArray<FocusDoctorData *>*array=[NSArray arrayWithContentsOfFile:[self getSavePath:urlString]];
//    if (array)
//    {
//        [self.dataList addObjectsFromArray:array];
//    }
//    else
//    {
        [self loadUrl:urlString params:paramDic];
//    }
    
    
}

#pragma mark - 沙盒保存路径
//根据URL的字符串生成一个保存图片文件的路径,cache  /cache/rtyuvfghjbgyuj
-(NSString *)getSavePath:(NSString *)urlString{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    //文件名 使用 md5来处理 工具类
    NSString *fileName = [urlString cz_md5String];
//    NSString *fileName=[urlString stringByAppendingString:@".plist"];
    
    return [cachePath stringByAppendingPathComponent:fileName];
}

#pragma mark - 获取网络数据
-(void)loadUrl:(NSString *)urlString
        params:(NSDictionary *)paramDic{
    
    [[NetWorkTool shareManager] POST_RequestWithUrlString:urlString parmas:paramDic successBloock:^(id responseObject) {
        
//       接收数据的筛选
        NSDictionary*dict=responseObject;
        NSArray*array=dict[@"data"];
//        字典数组转换为模型
        NSMutableArray<FocusDoctorData *> *mutableArray=[NSMutableArray array];
        NSArray<FocusDoctorData *> *modelArray = [NSArray yy_modelArrayWithClass:[FocusDoctorData class] json:array];
        [mutableArray addObjectsFromArray:modelArray];
        
   
        
//        将获取的数据转换为字符串写入沙盒

//        NSError *err = nil;
//        
//        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&err];
//        NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//        
//        [jsonStr writeToFile:[self getSavePath:urlString] atomically:YES encoding:NSUTF8StringEncoding error:NULL];
        
        
        //写入数据库
    
        //        NSLog(@"%@",[[DataBaseManager sharedManager] executeSQLString:jsonStr]?@"updata succeed":@"updata failed");
        //        NSLog(@"%@",[[DataBaseManager sharedManager] executeSQLStatements:jsonStr]?@"updata succeed":@"updata failed");
        [self initDataBaseWithModelArray:mutableArray];
        
        [self loadDataBase];
        
       
//        读取测试
//        NSString*string=[NSString stringWithContentsOfFile:[self getSavePath:urlString] encoding:NSUTF8StringEncoding error:&err];
        
//        [self.dataList addObjectsFromArray:modelArray];
        
        [self.tableView reloadData];
 
        
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"error = %@",error);
    }];
    
}

#pragma 数据库操作


-(void)initDataBaseWithModelArray:(NSMutableArray<FocusDoctorData*>*)modelArray
{
//    判断要写如的模型数组中是否在数据库中已经存在,如果已经存在,就从数组中删除
    int count=(int)modelArray.count;
//    NSMutableArray*delateID=[NSMutableArray array];
    for (int i=count; i>0; i--)
    {
        FocusDoctorData*data=modelArray[i-1];
        NSInteger doctor_id=[data.doctor_id integerValue];
        BOOL isExisted=[self queryDataBaseWithDoctor_ID:doctor_id];
        if (isExisted)
        {
            [modelArray removeObjectAtIndex:i-1];
//            [delateID addObject:@(i)];
        }
        
    }
    
//    for (NSUInteger i=delateID.count; i>0; i--)
//    {
//        
//        NSInteger ID=[delateID[i] intValue];
//        [modelArray removeObjectAtIndex:ID];
//    }
 
    
    
    
    /*
     NSArray *picArr = (NSArray *)dic[@"pic"];
     NSError *err = nil;
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:picArr options:NSJSONWritingPrettyPrinted error:&err];
     NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
     
     获取用第三方包 JSONKIT转换数组或字典
     FMResultSet *set = [app.db executeQuery:@"SELECT * FROM CACHE"];
     while ([set next]) {
     NSString *str  = [set stringForColumn:@"IMGURL"];
     //第三方包jsonKit转换
     NSArray *arr =(NSArray *)[str objectFromJSONString];
     }
     
     
     
     [_db executeUpdateWithFormat:@"INSERT INTO t_groupBuyModel (act_title,cover_image,avg_price,region_name,join_num,date_end,act_rebate,loupan_id,loupan_name,address,see_detail) VALUES (%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@);",model.act_title,model.cover_image,model.avg_price,model.region_name,model.join_num,model.date_end,model.act_rebate,model.loupan_id,model.loupan_name,model.address,model.see_detail];
     // 根据对应的模型遍历数组内的对象并创建数据
     for (int i = 0; i < model.images.count; i ++ ) {
     [_db executeUpdateWithFormat:@"INSERT INTO t_images (loupan_id,image) values (%@,%@)",model.loupan_id,model.images[i]];
     }
     */
    for (int i=0; i<modelArray.count; i++)
    {
        [[DataBaseManager sharedManager].dataBaseQueue inDatabase:^(FMDatabase *db) {
            
            BOOL isSucceed=[db executeUpdateWithFormat:@"INSERT INTO doctor (accuracy,banner,doctor_gender,doctor_hospital_name,doctor_id,doctor_name,doctor_portrait,doctor_title_name,easymob_id,flower,operation_count) VALUES (%@,%@,%@,%@,%@,%@,%@,%@,%@,%@,%@);",modelArray[i].accuracy,modelArray[i].banner,modelArray[i].doctor_gender,modelArray[i].doctor_hospital_name,modelArray[i].doctor_id,modelArray[i].doctor_name,modelArray[i].doctor_portrait,modelArray[i].doctor_title_name,modelArray[i].easymob_id,modelArray[i].flower,modelArray[i].operation_count];
            NSLog(@"%@",isSucceed?@"OK":@"Failed");
        }];
    }
}

#pragma mark - 加载全部数据

-(void)loadDataBase
{
    NSString*sqlString=@"select * from doctor";
    NSArray*resultArray=[[DataBaseManager sharedManager] queryRecords:sqlString];
    NSArray<FocusDoctorData *> *modelArray = [NSArray yy_modelArrayWithClass:[FocusDoctorData class] json:resultArray];
    [self.dataList addObjectsFromArray:modelArray];
}

#pragma mark - 更新数据库
-(void)updataDatabase
{
    //    NSString *sqlString = @"insert into t_person (name,age) values ('banzhang',99)";
    //[db executeUpdate:@"INSERT INTO myTable VALUES (?)", [NSNumber numberWithInt:3]];
    NSString*sqlString=[NSString stringWithFormat:@"insert into t_doctor(name,age) values ('%@',%@)",@"Apple",[NSNumber numberWithInt:1]];
    //    NSString *sqlString = @"insert into t_person (name,age) values ('?',?)", [NSNumber numberWithInt:3], [NSNumber numberWithInt:3];
    //    手动直接调用DataBaseManager的executeSQLString方法
    //    封装的执行sql语句的方法,内部调用queue 执行 inDatabase executeUpdata的方法
    NSLog(@"%@",[[DataBaseManager sharedManager] executeSQLString:sqlString]?@"updata succeed":@"updata failed");
    
    //    手动调用DataBaseManager的queue执行inDatabase executeUpdata的方法
    [[DataBaseManager sharedManager].dataBaseQueue inDatabase:^(FMDatabase *db) {
        NSLog(@"%@",[db executeUpdate:sqlString]?@"OK":@"Failed");
    }];
    //    查询所有数据
//    [self queryDataBase];
    
}


#pragma mark - 删除表中的某一项
-(void)deleteDoctorTableWithDoctor_ID:(NSInteger)doctor_id
{
    //DELETE FROM COMPANY WHERE ID = 7
    NSString*sqlString=[NSString stringWithFormat:@"delete from doctor where doctor_id=%ld",doctor_id];
    NSLog(@"%@",[[DataBaseManager sharedManager] executeSQLString:sqlString]?@"updata succeed":@"updata failed");
}

-(BOOL)queryDataBaseWithDoctor_ID:(NSInteger)doctor_id
{
    NSMutableArray<FocusDoctorData *> *array=[NSMutableArray array];
    NSString*sqlString=[NSString stringWithFormat:@"select * from doctor where doctor_id=%ld",doctor_id];
    NSArray*resultArray=[[DataBaseManager sharedManager] queryRecords:sqlString];
    NSArray<FocusDoctorData *> *modelArray = [NSArray yy_modelArrayWithClass:[FocusDoctorData class] json:resultArray];
    [array addObjectsFromArray:modelArray];
    if (array.count>0)
    {
        return YES;
    }
    else
        return NO;
}
#pragma mark - 清空数据库列表
-(void)cleanoutDoctorTable
{
    NSString*sqlString=@"delete from doctor";
//    NSString*sqlString=[NSString stringWithFormat:@"insert into t_doctor(name,age) values ('%@',%@)",@"Apple",[NSNumber numberWithInt:1]];
    //    NSString *sqlString = @"insert into t_person (name,age) values ('?',?)", [NSNumber numberWithInt:3], [NSNumber numberWithInt:3];
    //    手动直接调用DataBaseManager的executeSQLString方法
    //    封装的执行sql语句的方法,内部调用queue 执行 inDatabase executeUpdata的方法
    NSLog(@"%@",[[DataBaseManager sharedManager] executeSQLString:sqlString]?@"updata succeed":@"updata failed");
}

#pragma mark tableView的代理方法
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //model
    
    
    
    
    FocusDoctorData *model = self.dataList[indexPath.row];
    
    NSString *identifier = cellID;
    
    
    FocusDoctorCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    
    cell.dataModel =model;
    
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //    NSLog(@"%@",self.dataList[1]);
    return  self.dataList.count;
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    FocusDoctorData *model = self.dataList[indexPath.row];
    self.index=indexPath;
    
    FocusDoctorDetailController *detailVc = [[FocusDoctorDetailController alloc] init];

    detailVc.data=model;


    detailVc.delegate=self;
    
    [self.navigationController pushViewController:detailVc animated:YES];
}

#pragma mark - 删除关注医生的代理方法
-(void)deletaDataList
{
    NSString*doctorName=self.dataList[_index.row].doctor_name;
    [self showAlertVCWithDoctorName:doctorName];
    
//    //方法一 删除内存中的对应数据列表,显示,清空数据库,重写数据库
//    [self.dataList removeObjectAtIndex:_index.row];
//
//
////    操作数据库
//    [self cleanoutDoctorTable];
//    [self initDataBaseWithModelArray:self.dataList.copy];
//    
//
////    重新加载
//    [self.tableView reloadData];
    
    //方法二 清空内存中的数据列表,查询删除数据库中的对应项目,读取数据库到内存数据列表,显示
    //    清空内存数据列表
    
    
//    操作数据库
    NSInteger doctor_id=[self.dataList[_index.row].doctor_id integerValue];
    
    [self deleteDoctorTableWithDoctor_ID:doctor_id];
    [self.dataList removeAllObjects];
    //    读取数据库到内存
    [self loadDataBase];
    
    [self.tableView reloadData];

}

#pragma mark - 弹窗提示
-(void)showAlertVCWithDoctorName:(NSString*)doctorName;
{
    //弹框
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:doctorName message:@"取消关注成功" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sureBtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVc addAction:sureBtn];
    
    AppDelegate*delegate=(AppDelegate *)[UIApplication sharedApplication].delegate;

    
    [delegate.window.rootViewController presentViewController:alertVc animated:YES completion:^{
    }];
    
}



@end
